package com.mtao.controller.admin;

import com.mtao.SysUserService;
import com.mtao.utils.JwtUtils;
import com.mtao.utils.StringUtil;
import com.mtao.entity.Result;
import com.mtao.entity.SysRole;
import com.mtao.entity.SysUser;
import jakarta.annotation.Resource;
import org.springframework.security.core.Authentication;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private JwtUtils jwtUtils;
    @Resource
    private SysUserService sysUserService;

    /**
     * 获取当前用户信息
     * @param token
     * @return
     */
    @PostMapping("/userInfo")
    public Result<SysUser> userInfo(@RequestHeader(name="Authorization") String token){
        String str = StringUtil.splitString(token, "Bearer ");
        Authentication authentication = jwtUtils.getAuthentication(str);
        String name = authentication.getName();
        SysUser user = sysUserService.findByName(name);
        user.setPassword("******");
        return Result.success(user);
    }

    /**
     * 获取用户列表
     * @return
     */
    @PostMapping("/list")
    public Result<List<SysUser>> userList(){
        List<SysUser> user = sysUserService.getUser();
        return Result.success(user);
    }
    /**
     * 创建用户
     * @return
     */
    @PostMapping("/create")
    public Result createUser(@RequestBody @Validated(SysRole.Add.class) SysUser sysUser){
        String username = sysUser.getUsername();
        SysUser user = sysUserService.findByName(username);
        if(Objects.isNull(user)){
            sysUserService.createUser(sysUser);
            return Result.success();
        }
        return Result.error("当前用户已存在");
    }
}
